<?php

namespace app\data\service;

use think\admin\Service;
use think\facade\Log;

/**
 * 采集记录
 * Class RecordService
 * @package app\data\service
 */
class RecordService extends Service
{
    /**
     * 批量分析原因
     * @return void
     */
    public function analyzeReasonBatch()
    {
        foreach ($this->app->db->name('data_record')->whereIn('paint_status', [-1, 0])->where('analyze_reason', 0)->cursor() as $vo) try {

            $analyzeReason = $this->analyzeReason($vo['invite_remark']);
            if (!empty($analyzeReason)) {
                $this->app->db->name('data_record')->where('id', $vo['id'])->update(['analyze_reason' => $analyzeReason]);
            }

        } catch (\Exception $exception) {
            Log::error("分析原因 {$vo['id']} 失败: " . json_encode([
                    'message' => $exception->getMessage(),
                    'file' => $exception->getFile(),
                    'line' => $exception->getLine(),
                    'trace' => $exception->getTraceAsString(),
                ]));
        }
    }

    /**
     * 分析原因
     * @param $inviteRemark
     * @return int
     */
    public function analyzeReason($inviteRemark)
    {
        $analyzeReasons = [
            1 => [
                '无人接听',
                '未采集到信息',
            ],
            2 => [
                '不愿意',
                '去',
            ],
            3 => [
                '今天',
                '明天',
                '后天',
                '有时间',
                '现在',
                '上午',
                '下午',
                '晚上',
                '时间',
                '外地',
            ],
            4 => [
                '不知道',
                '车牌号错误',
            ],
        ];

        foreach ($analyzeReasons as $reason => $keywords) {
            foreach ($keywords as $keyword) {
                if (strpos($inviteRemark, $keyword) !== false) {
                    return $reason;
                }
            }
        }

        return 0;
    }

    /**
     * 原因类型
     * @param $reasonId
     * @return string|string[]
     */
    public function analyzeReasons($reasonId = null)
    {
        // 未喷漆原因(1=其他原因;2=司机原因;3=延期喷漆;4=甲方原因)
        $analyzeReasons = [
            0 => '',
            1 => '其他原因',
            2 => '司机原因',
            3 => '延期喷漆',
            4 => '甲方原因',
        ];

        if (is_null($reasonId)) {
            return $analyzeReasons;
        }

        return $analyzeReasons[$reasonId] ?? '';
    }

    /**
     * 格式化数据
     * @param array $list
     * @return array
     */
    public function format(array &$list)
    {
        $uuidsDocking = array_column($list, 'uuid_docking');
        $uuidCity = array_column($list, 'uuid_city');
        $userIds = array_unique(array_merge($uuidCity, $uuidsDocking));

        $workUsers = $this->app->db->name('work_user')->whereIn('id', $userIds)->select()->toArray();
        foreach ($workUsers as $workUser) {
            $userId2Name[$workUser['id']] = $workUser['name'];
        }
        //$allIds = array_column($list, 'id');
        foreach ($list as &$item) {
            $item['paint_status_text'] = StringParse::instance()->shiFou2Text($item['paint_status']);
            $item['fail_status_text'] = StringParse::instance()->shiFou2Text($item['fail_status']);
            $item['has_cover_text'] = StringParse::instance()->shiFou2Text($item['has_cover']);
            $item['ad_cover_fee_text'] = StringParse::instance()->shiFou2Text($item['ad_cover_fee']);
            $item['name_docking'] = $userId2Name[$item['uuid_docking']] ?? '';
            $item['name_city'] = $userId2Name[$item['uuid_city']] ?? '';


            if (is_null($item['time_invite'])) {
                $timestamp = strtotime($item['time_docking']);
                $now = time();
                $remainingTimestamp = 1800 - ($now - $timestamp);
                $item['remaining_timestamp'] = $remainingTimestamp;

                if ($remainingTimestamp < 0) {
                    // 超过30分钟，红色，取消倒计时
                    $item['remaining_timestamp'] = $remainingTimestamp;
                } else if (0 < $remainingTimestamp && $remainingTimestamp < 900) {
                    // 超过15分钟，粉色，显示倒计时
                    $item['remaining_timestamp'] = $remainingTimestamp;
                } else {
                    // 15分钟内，绿色，显示倒计时
                }
            } else {
                $item['remaining_timestamp'] = null;
            }
            $item['reason'] = "";
            if(input("is_rework") == 1) {
                $item['reason'] = $this->app->db->name('rework_record')->where('record_id', $item["id"])->order('id', 'desc')->limit(1)->value("reason");
            }
        }
    }

    /**
     * 格式化单一数据
     * @param array $list
     * @return array
     */
    public function formatOne(array $data)
    {
        $uuidsDocking = $data['uuid_docking'] ?? 0;
        $uuidCity = $data['uuid_city'] ?? 0;
        $userIds = array_unique([$uuidCity, $uuidsDocking]);

        $workUsers = $this->app->db->name('work_user')->whereIn('id', $userIds)->select()->toArray();
        foreach ($workUsers as $workUser) {
            $userId2Name[$workUser['id']] = $workUser['name'];
        }

        $data['paint_status_text'] = StringParse::instance()->youWu2Text($data['paint_status'] ?? '');
        $data['fail_status_text'] = StringParse::instance()->shiFou2Text($data['fail_status'] ?? '');
        $data['has_cover_text'] = StringParse::instance()->shiFou2Text($data['has_cover'] ?? '');
        $data['ad_cover_fee_text'] = StringParse::instance()->shiFou2Text($data['ad_cover_fee'] ?? '');
        $data['name_docking'] = $userId2Name[$data['uuid_docking']] ?? '';
        $data['name_city'] = $userId2Name[$data['uuid_city']] ?? '';

        return $data;
    }

    /**
     * 判断是否存在记录
     * @param $phone
     * @param $plateNumber
     * @return array|false|\think\Db|\think\Model
     */
    public function isExist($phone, $plateNumber)
    {
        $record = $this->app->db->name('data_record')
//            ->where('phone', $phone)
            ->where('plate_number', $plateNumber)
//            ->whereIn('paint_status', [0, -1])
            ->where('create_at', '>', date('Y-m-d H:i:s', strtotime("-2 months", time())))
            ->order('id desc')
            ->findOrEmpty();
        if ($record) {
            return $record;
        }

        return false;
    }

    /**
     * 格式化转发样式
     * @param $data
     * @return string
     */
    public function toForwardText($data, $level = 'operate')
    {
        $id = $data['id'];
        $username = $data['username'];
        $plateNumber = $data['plate_number'];
        $phone = $data['phone'];
        $carVehicleType = $data['car_vehicle_type'];
        $provinceOwner = $data['province_owner'] . $data['city_owner'];
        $province = $data['province'] . $data['city'];
        $timePlan = date('Y-m-d', strtotime($data['time_plan']));
        $carHasAd = StringParse::instance()->youWu2Text($data['car_has_ad']);
        $isAwareOf2YearAgreement = StringParse::instance()->shiFou2Text($data['is_aware_of_2_year_agreement']);
        $isPlateNumberConsistent = StringParse::instance()->shiFou2Text($data['is_plate_number_consistent']);

//        if ($level == 'operate') {
//            $url = config('fei_shu.url') . "/admin.html?show=operate&show_id={$id}#/data/record.car_record_operate/index.html?show_id={$id}";
//        } else if ($level == 'docking') {
//            $url = config('fei_shu.url') . "/admin.html?show=docking&show_id={$id}#/data/record.car_record_docking/index.html?show_id={$id}";
//        } else {
//            $url = config('fei_shu.url') . "/admin.html?show=city_owner&show_id={$id}#/data/record.car_record_city_owner/index.html?show_id={$id}";
//        }

        // http://youkejia.test/admin.html?show=car_record_complete&id=16932#/data/record.car_record_complete/edit.html?id=16932
        $url = config('fei_shu.url') . "/admin.html?show=car_record_complete&id={$id}#/data/record.car_record_complete/edit.html?id={$id}";


        return "ID: {$id}
司机姓名：{$username}
司机车牌：{$plateNumber}
手机号码：{$phone}
车长车身颜色：{$carVehicleType}
预约城市：{$province}
预约喷漆时间：{$timePlan}
车上有无广告：{$carHasAd}
是否知道签署协议：{$isAwareOf2YearAgreement}
链接： <a href='{$url}'>点击这里</a>";
    }

    /**
     * 保存邀约情况
     * @param $record
     * @param $inviteRemark
     * @return bool
     * @throws \think\db\exception\DbException
     */
    public function saveInviteRemark($record, $inviteRemark)
    {
        if (empty($record) || empty($inviteRemark)) {
            return false;
        }

        $now = date('Y-m-d H:i:s');

        if ($record['invite_remark'] == $inviteRemark) {
            if (empty($record['time_invite'])) {
                $data['time_invite'] = $now;
            }
            return false;
        }

        if (empty($record['invite_remark'])) {
            $data['invite_remark'] = $inviteRemark;
            $data['time_invite'] = $now;
        }
        if (empty($record['time_invite'])) {
            $data['time_invite'] = $now;
        }

        if (!empty($record['invite_remark'])) {
            $data['invite_remarks'] = $record['invite_remarks'] . PHP_EOL .  $inviteRemark;
        }

        if (!empty($record['time_invite'])) {
            $data['time_invites'] = $record['time_invites'] . PHP_EOL . $now;
        }

        if (!empty($data)) {
            $result = $this->app->db->name('data_record')->where('id', $record['id'])->update($data);

            if (!$result) {
                return false;
            }
        }

        return true;
    }

    /**
     * 师傅自动结单处理
     * @param $data
     * @return void
     * @throws \think\db\exception\DbException
     */
    public function saveCompleteData($data)
    {
        $record = $this->app->db->name('data_record')->where('plate_number', $data['plate_number'])->order('id desc')->findOrEmpty();
        if ($record) {
            $record['cover_num'] = intval($record['cover_num']);
            $record['cover_price'] = intval($record['cover_price']);
            if (is_null($record['time_complete']) && isset($data['paint_status']) && ($data['paint_status'] == 1 || $data['paint_status'] == -1)) {
                $data['time_complete'] = date('Y-m-d H:i:s');
            }
            foreach ($data as $key => $datum) {
                if ($datum === '') {
                    unset($data[$key]);
                }
            }
            if (!empty($data)) {

                if (isset($data['paint_status']) && $data['paint_status'] == 1) {
                    if (!isset($data['car_vehicle_type_id'])) {
                        $data['car_vehicle_type_id'] = $record['car_vehicle_type_id'];
                    }
                    if (!isset($data['end_paint_status'])) {
                        $data['end_paint_status'] = $record['end_paint_status'];
                    }
                }

                $data = CityUserRelationService::instance()->calcPaintPrice($record, $data);
                $this->app->db->name('data_record')->where('id', $record['id'])->update($data);
            }
        }
    }
}